package com.atguigu.lease.web.app.service.impl;


import ch.qos.logback.core.util.SystemInfo;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtilApp;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.utils.HttpUtils;
import com.atguigu.lease.web.app.utils.VerifyCodeUtil;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SmsService smsService;

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void getCode(String phone) {
        // 判断手机号是否为空
        if (phone == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        //2. 检查Redis中是否已经存在该手机号码的key
        // 这一步的目的是为了避免频繁发送短信
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        boolean hasKey = stringRedisTemplate.hasKey(key);
        if (hasKey) {
            //若存在，则检查其存在的时间
            Long expire = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                //若存在时间不足一分钟，响应发送过于频繁
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }

        String code = VerifyCodeUtil.getVerifyCode(6);
        //3.发送短信，并将验证码存入Redis
        smsService.sendCode(phone,code);

    }

    @Override
    public String login(LoginVo loginVo) {
        // 判断是否输入短信验证码
        Assert.notNull(loginVo.getCode(), String.valueOf(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND));
        // 在 Redis 中校验验证码是否正确
        String code = stringRedisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone());
        // Assert.isTrue(code.equals(loginVo.getCode()), String.valueOf(ResultCodeEnum.APP_LOGIN_CODE_ERROR));
        // 检查验证码是否存在
        if (code == null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }

        // 检查验证码是否正确
        if (!code.equals(loginVo.getCode())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        // 验证码正确，查询用户信息(用户是否存在)
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(queryWrapper);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());

            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户-"+loginVo.getPhone().substring(5));
            userInfoService.save(userInfo);
        }

        //4.判断用户是否被禁
        if (userInfo.getStatus().equals(BaseStatus.DISABLE)) {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        // 创建TOKEN
        return JwtUtilApp.createToken(userInfo.getPhone(), loginVo.getCode());
    }

    @Override
    public UserInfoVo infoByPhone(String phone) {
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone, phone);
        UserInfo userInfo = userInfoService.getOne(queryWrapper);
        if (userInfo != null) {
            return new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());
        }
        return null;
    }


}

